package com.bjpowernode.boss.mvc.interceptors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.boss.client.RedisClient;
import com.bjpowernode.boss.constant.KeyConstant;
import com.bjpowernode.boss.enums.RespInfo;
import com.bjpowernode.boss.mvc.models.response.AjaxResult;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisClient redisClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        String operatorId = request.getHeader("operatorId");
        String token = request.getHeader("Authorization");

        if (StrUtil.isNotBlank(operatorId) && StrUtil.isNotBlank(token) && token.startsWith("Bearer ")) {

            String tokenJwt = token.substring(7);
            String jwt = (String)redisClient.getHashAll(KeyConstant.OPERATOR_TOKEN + operatorId, "jwt");

            if (StrUtil.isNotBlank(jwt) && jwt.equals(tokenJwt)) {
                return true;
            }
        }

        AjaxResult fail = AjaxResult.FAIL(RespInfo.OPERATOR_TOKEN_INVALID);
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSONUtil.toJsonStr(fail));
        out.flush();
        out.close();

        return false;
    }

}
